package com.zrf.base.knowledge.sort;

import com.zrf.base.knowledge.collections.MyHashMap;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zrf on 2016/5/11.
 * 大量不重复的数据排序
 *
 * @author zrf
 */
public class Sort {
    /**
     * 文件的行数
     */
    private static final int FILE_LINES = 500000000;

    /**
     * 初始化文件中的内容
     */
    public void initFile() {
        FileOutputStream fos = null;
        try {
            File file = new File("/tmp/test/file.txt");
            if (!file.exists()) {
                file.createNewFile();
            }

            Integer size = FILE_LINES;
            Map<Integer, Integer> map = new MyHashMap<>();
            for (Integer i = 0; i < size; i++) {
                map.put(i, i);
            }

            fos = new FileOutputStream(file);
            FileOutputStream finalFos = fos;
            map.forEach((key, value)->{
                try {
                    finalFos.write(new String(key.toString() + "\n").getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 排序
     * @since 1.8+
     */
    public void sort() {
        BufferedReader bufferedReader = null;
        try {
            File file = new File("/tmp/test/file.txt");
            long begin = System.currentTimeMillis();
            bufferedReader = new BufferedReader(new FileReader(file));
            List<Boolean> list = new ArrayList<>(FILE_LINES);
            String line = bufferedReader.readLine();
            while (line != null) {
                Integer index = Integer.parseInt(line);
                list.set(index, true);
                line = bufferedReader.readLine();
            }
            long end = System.currentTimeMillis();
            System.out.println(end - begin);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * main方法
     * @param args 参数
     */
    public static void main(String[] args) {
        new Sort().initFile();
    }
}
